import React, { Component } from "react";
import "./codeMessage.scss";
import { Toast, InputItem } from "antd-mobile";
import { createForm } from "rc-form";
import { connect } from "react-redux";
import { checkTool } from "plugin-tool-check";
import { setLoginRegisterDatas } from "../../Redux/Action/login/loginRegister";
import yhTools from "../../tools/yh";

class CodeMessage extends Component {
	constructor(props) {
		super(props);
		this.seconds = 59; //默认59秒
		this.needPhoneNumUrl = this.props.codeMessageOption.needPhoneNumUrl
			? this.props.codeMessageOption.needPhoneNumUrl
			: ""; //需要手机号发送短信接口
		this.noPhoneNumUrl = "/verifyCode/applyloan/0"; //不需要手机号发送短信接口
		this.moduleName = this.props.codeMessageOption.moduleName
			? this.props.codeMessageOption.moduleName
			: ""; //模块名称
		this.type = this.props.codeMessageOption.type
			? this.props.codeMessageOption.type
			: ""; //验证码类型 dialog为弹窗
		this.addClass = this.props.codeMessageOption.addClass
			? this.props.codeMessageOption.addClass
			: ""; //扩展样式
		this.maxLength = this.props.codeMessageOption.maxLength
			? this.props.codeMessageOption.maxLength
			: "6";
		this.codeNumber = this.props.codeMessageOption.codeNumber
			? this.props.codeMessageOption.codeNumber
			: "";
		this.isLogin = this.props.codeMessageOption.isLogin
			? this.props.codeMessageOption.isLogin
			: "";
		this.timeObj = "";
		if (this.type == "dialog") {
			this.state = {
				codeNumber: "", //短信验证码
				codeBtnText: "获取验证码", //按钮显示文案
				btnDisable: false, //获取按钮是否禁用  默认false 不禁用
				codeCheck: true //验证码校验标识
			};
		} else {
			this.state = {
				classNameIcon:
					"input-icon " +
					(this.props.codeMessageOption.classNameIcon
						? this.props.codeMessageOption.classNameIcon
						: ""),
				placeHolder: this.props.codeMessageOption.placeHolder
					? this.props.codeMessageOption.placeHolder
					: "", //扩展图标样式
				codeNumber: this.codeNumber, //短信验证码
				codeBtnText: "获取验证码", //按钮显示文案
				btnDisable: false, //获取按钮是否禁用  默认false 不禁用
				codeCheck: true, //验证码校验标识
				phoneNum: this.props.codeMessageOption.phoneNum
					? this.props.codeMessageOption.phoneNum
					: "",
				jsonData: this.props.codeMessageOption.jsonData
					? this.props.codeMessageOption.jsonData
					: ""
			};
		}
	}

	componentWillReceiveProps(data) {
		if (this.type == "dialog") {
			//弹窗验证码  不需要手机号
			this.setState({
				codeCheck: data.codeMessageOption.codeCheck
			});
		} else {
			//表单验证码 需要手机号
			this.setState({
				phoneNum: data.codeMessageOption.phoneNum,
				codeCheck: data.codeMessageOption.codeCheck,
				codeNumber: data.codeMessageOption.codeNumber, //短信验证码
				jsonData: data.codeMessageOption.jsonData
					? this.props.codeMessageOption.jsonData
					: ""
			});
		}
	}

	componentDidMount() {
		if (this.type == "dialog") {
			if (sessionStorage.getItem("codeMessageSeconds")) {
				this.seconds = sessionStorage.getItem("codeMessageSeconds");
				this.timeRun();
			} else {
				this.sendNoPhoneClick();
				return false;
			}
		}
		if (yhTools.platform() == "ios") {
			//这个判断作用：ios系统当页面切换到后台时应用被暂停，倒计时不在执行，这里进行仿真处理
			if (process.env.NODE_ENV != "development") {
				let _that = this;
				window.YHAuthorize.View.addEventListener("ApplicationActive", () => {
					let lastTime = this.props.loginRegisterDatas.loginLastTime;
					let secondstamp = this.props.loginRegisterDatas.seconds;
					let nowTime = new Date().getTime();
					if (lastTime.typeOf("number") && lastTime != 0) {
						//说明被点击过
						let timestamp = parseInt((nowTime - lastTime) / 1000);
						let T = secondstamp - timestamp;
						clearTimeout(_that.timeObj);
						if (T < 0) {
							_that.seconds = 0;
							_that.timeRun();
						} else {
							_that.seconds = T;
							_that.timeRun();
						}
					}
				});
				window.YHAuthorize.View.addEventListener(
					"ApplicationBackground",
					() => {
						let nowTime = new Date().getTime();
						this.props._setLoginRegisterDatas({
							loginLastTime: "" + nowTime,
							seconds: _that.seconds
						}); //当页面被切换到后台，记录当前的倒计时时间
					}
				);
			}
		}
	}

	componentWillUnmount() {
		clearTimeout(this.timeObj);
		sessionStorage.setItem("codeMessageSeconds", this.seconds);
	}

	//不需要手机号 发送短信
	sendNoPhoneClick() {
		if (process.env.NODE_ENV != "development") {
			yhTools.TDAPPonEvent("Get_verification_code");
		}
		if (this.state.btnDisable) {
			//防重提交
			return false;
		}
		if (this.state.codeBtnText == "重新获取") {
			// yhTools.getStatisticsDatas(this.moduleName+'_CodeAgainButton_Click',this.props.codeMessageOption.propsObj);//“获取验证码”按钮点击量统计
		}
		/*else{
                    yhTools.getStatisticsDatas('GetCodeButton_Click',this.props.codeMessageOption.propsObj);//“获取验证码”按钮点击量统计
                }*/
		const params = {
			url: this.noPhoneNumUrl,
			header: this.props.codeMessageOption.propsObj.getAppPlatformsDatas,
			params: {},
			_alertShow: false
		};
		yhTools.request(params).then(res => {
			if (res.code == 0) {
				// yhTools.toast("短信已发送");
				Toast.info("短信已发送", 2);
				this.timeRun();
				if (this.props.codeMessageOption.sendCallback) {
					this.props.codeMessageOption.sendCallback();
				}
			} else if (res.code == "20003") {
				//今日获取次数过多,请明天再试!
				yhTools.alertOneButt(res.message, "好的");
			} else {
				yhTools.alertOneButt(res.message, "好的");
			}
		});
	}

	//需要手机号发送短信
	sendClick() {
		let dataJson;
		if (this.state.jsonData != "") {
			if (!this.state.jsonData.username) {
				Toast.info("请输入姓名", 2);
				return;
			}
			if (!this.state.jsonData.accountNo) {
				Toast.info("请输入银行卡号", 2);
				return;
			}
			dataJson = this.state.jsonData;
		} else {
			dataJson = { mobilePhone: this.state.phoneNum };
		}

		if (!this.state.phoneNum.toString()) {
			if (this.isLogin != "") {
				Toast.info("请输入注册手机号", 2);
			} else {
				Toast.info("请输入手机号", 2);
			}
			if (this.props.codeMessageOption.phoneErrCallBack) {
				this.props.codeMessageOption.phoneErrCallBack();
			}
			return false;
		} else if (
			!checkTool.isPhoneNo({ valueParams: "" + this.state.phoneNum })
		) {
			Toast.info("手机号输入有误", 2);
			return false;
		}
		if (this.state.btnDisable) {
			return false;
		}
		//当点击了获取验证码按钮时，将点击事件回调回去，修改触发页面中的某些标记;例如注册页面表单校验时，需要知道是否点击过获取验证码按钮，如果没有点击，要进行提示
		if (this.props.codeMessageOption.codeMessageBtnCallBack) {
			this.props.codeMessageOption.codeMessageBtnCallBack(true);
		}
		const params = {
			url: this.needPhoneNumUrl,
			header: this.props.codeMessageOption.propsObj.getAppPlatformsDatas,
			params: dataJson,
			_alertShow: false
		};
		yhTools.request(params).then(res => {
			if (res.code == 0) {
				Toast.info("短信已发送", 2);
				this.timeRun();
			} else if (res.code == "20003") {
				//今日获取次数过多,请明天再试!
				yhTools.alertOneButt(res.message, "好的");
			} else {
				yhTools.toast(res.message, 2);
			}
		});
	}

	timeRun() {
		if (this.seconds == 0) {
			this.setState({
				codeBtnText: "重新获取",
				btnDisable: false
			});
			this.seconds = 59;
			this.props._setLoginRegisterDatas({ loginLastTime: 0, seconds: 0 });
		} else {
			this.setState({
				codeBtnText: this.seconds + "秒",
				btnDisable: true
			});
			this.seconds--;
			this.timeObj = setTimeout(() => {
				this.timeRun();
			}, 1000);
		}
	}

	//验证码文本框获取光标
	inputFocus() {
		this.setState({
			codeCheck: true
		});
		if (this.type != "dialog") {
			if (process.env.NODE_ENV != "development") {
				window.YHAuthorize.Keyboard.isEdit = "1";
			}
		}
	}

	//表单验证码文本框获取光标
	inputFormFocus() {
		this.setState({
			codeCheck: true
		});
		if (this.props.codeMessageOption.inputFocusCallBack) {
			this.props.codeMessageOption.inputFocusCallBack();
		}
	}

	//表单验证码文本框失去光标
	inputFormBlur() {
		if (this.props.codeMessageOption.inputBlurCallBack) {
			this.props.codeMessageOption.inputBlurCallBack();
		}
	}

	//验证码文本框改变事件
	inputChange(value) {
		this.setState({
			codeNumber: value.trim(),
			codeCheck: true
		});
		if (this.props.codeMessageOption.codeCallback) {
			this.props.codeMessageOption.codeCallback(value);
		}
	}

	render() {
		let content = "";
		if (this.type == "dialog") {
			content = (
				<div
					className={
						this.state.codeNumber == "" && !this.state.codeCheck
							? "dialog-code-message-content err-placeholder"
							: "dialog-code-message-content"
					}
				>
					<input
						type="number"
						placeholder="请输入短信验证码"
						maxLength={this.maxLength ? this.maxLength : "6"}
						className={
							this.state.codeNumber != "" && !this.state.codeCheck
								? "err-value"
								: ""
						}
						onFocus={this.inputFocus.bind(this)}
						onBlur={this.inputFormBlur.bind(this)}
						value={this.state.codeNumber}
						onChange={this.inputChange.bind(this)}
					/>
					<button
						className={this.state.btnDisable ? "code-btn seconds" : "code-btn"}
						id="dialogSendBtn"
						onClick={this.sendNoPhoneClick.bind(this)}
					>
						{this.state.codeBtnText}
					</button>
				</div>
			);
		} else {
			content = (
				<div className="form-code-content">
					<div
						className={
							this.state.codeNumber == "" && !this.state.codeCheck
								? "input-fa"
								: "input-fa"
						}
					>
						{this.props.codeMessageOption.leftIcon ? (
							<img
								className={this.state.classNameIcon}
								src={this.props.codeMessageOption.leftIcon}
							/>
						) : (
							<span className="label">验证码</span>
						)}
						<InputItem
							name="code_input"
							type="money"
							moneyKeyboardAlign="left"
							placeholder={
								this.state.placeHolder
									? this.state.placeHolder
									: "预留手机验证码"
							}
							maxLength={this.maxLength ? this.maxLength : "6"}
							onFocus={this.inputFormFocus.bind(this)}
							onBlur={this.inputFormBlur.bind(this)}
							value={this.state.codeNumber}
							onChange={this.inputChange.bind(this)}
						></InputItem>
						{this.props.codeMessageOption.classNameRightBtn ? (
							<button
								className={
									this.state.btnDisable
										? "code-btn seconds " +
										  this.props.codeMessageOption.classNameRightBtn
										: "code-btn " +
										  this.props.codeMessageOption.classNameRightBtn
								}
								id="formSendBtn"
								onClick={this.sendClick.bind(this)}
							>
								{this.state.codeBtnText}
							</button>
						) : (
							<button
								className={
									this.state.btnDisable ? "code-btn seconds" : "code-btn"
								}
								id="formSendBtn"
								onClick={this.sendClick.bind(this)}
							>
								{this.state.codeBtnText}
							</button>
						)}
					</div>
				</div>
			);
		}
		return (
			<div className={"code-message-content " + this.addClass}>{content}</div>
		);
	}
}

function mapStateToProps(state) {
	return state;
}

function mapDispatchToProps(dispatch) {
	return {
		_setLoginRegisterDatas: options => {
			//获取设备信息
			dispatch(setLoginRegisterDatas(options));
		}
	};
}

export default connect(
	mapStateToProps,
	mapDispatchToProps
)(createForm()(CodeMessage));
